package com.damacheng009.future.alarm.job;

import java.util.List;

import org.nutz.dao.Dao;

import com.damacheng009.future.alarm.crawler.SinaRealtimeCrawler;
import com.damacheng009.future.alarm.domain.TAlarm;
import com.damacheng009.future.alarm.toolkit.DaoTool;
import com.damacheng009.future.alarm.toolkit.MailTool;
import com.damacheng009.future.alarm.vo.KLineVo;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.NumberUtil;

public class RealtimeJob {
	
	public void run() {
		System.out.println("实时任务执行");
		try {
			SinaRealtimeCrawler crawler = new SinaRealtimeCrawler();
			Dao dao = DaoTool.createDao(null);
			
			// 找出预警表的所有项目
			List<TAlarm> alarmList = dao.query(TAlarm.class, null);
			
			// 实时获取行情数据
			for (TAlarm alarm : alarmList) {
				KLineVo nowLine = crawler.getKLine(alarm.getCode());
				
				if (nowLine != null) {
					// 以下为价格预警操作
					Float closePrice = Float.parseFloat(nowLine.getC());
					
					if (alarm.getUpClose() != null && NumberUtil.compare(closePrice, alarm.getUpClose()) == 1) {
						// 现价大于上限，预警
						String msg = alarm.getCode() + "价格突破上限，现价为:" + closePrice;
						MailTool.send("价格预警", msg);
						// 把对应的字段设为NULL
						alarm.setUpClose(null);
						dao.update(alarm);
						continue;
					}
					
					if (alarm.getDownClose() != null && NumberUtil.compare(closePrice, alarm.getDownClose()) == -1) {
						// 现价小于下限，预警
						String msg = alarm.getCode() + "价格突破下限，现价为:" + closePrice;
						MailTool.send("价格预警", msg);
						// 把对应的字段设为NULL
						alarm.setDownClose(null);
						dao.update(alarm);
						continue;
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			// 发邮件
			MailTool.send("实时行情job异常", ExceptionUtil.stacktraceToString(e));
		}
		
	}

}
